package com.bigstar.lolen_e;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.google.ads.AdRequest;
import com.google.ads.AdView;

public class RankingBoard extends ListActivity {
	ArrayList<RankInfo> rankArray = new ArrayList<RankInfo>();
	ListAdapter adapter;
	int state = 0;
	int page = 0;
	int max_page = 0;
	AutoCompleteTextView et_search;
	String url;
	private ProgressDialog pd;
	boolean name_search = false;
	String search_name = "";
	EditText et;
	String country;
	String game_type;
	@Override 
	public void onCreate(Bundle savedInstanceState) { 
		super.onCreate(savedInstanceState); 
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 
        ChampionData.load(this);
        ItemData.load(this);
        Rune.load(this);
		setContentView(R.layout.ranking_board); 
        AdView adview = (AdView)findViewById(R.id.adView);
        AdRequest re = new AdRequest(); 
        adview.loadAd(re);
		page = 0;
		max_page = 0;
		state = 2;
		search_name = "";
		adapter = new ListAdapter(this);
		setListAdapter(adapter);
		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		country = pref.getString("rank_country", "na");
		process("http://competitive.na.leagueoflegends.com/ladders/"+country+"/current/rankedsolo5x5");
		game_type = "rankedsolo5x5";
		et_search = (AutoCompleteTextView)findViewById(R.id.et_name);
//		setAdapter();
		RankingBoard.this.findViewById(R.id.btn_solo5x5).setBackgroundResource(R.drawable.rank_tab_ov);
		name_search = false;
		
		Button b = (Button)this.findViewById(R.id.btn_team3x3);
		b.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				state = 0;
				page = 0;
				max_page = 0;
				name_search = false;
				search_name = "";
				game_type = "ranked_team_3x3";
				v.setBackgroundResource(R.drawable.rank_tab_ov);
				RankingBoard.this.findViewById(R.id.btn_team5x5).setBackgroundResource(R.drawable.rank_tab);
				RankingBoard.this.findViewById(R.id.btn_solo5x5).setBackgroundResource(R.drawable.rank_tab);
				((TextView)RankingBoard.this.findViewById(R.id.tv_ladder_name)).setText("Team Name");
				((TextView)RankingBoard.this.findViewById(R.id.tv_search)).setText("Team Name:");
				et_search.setText("");
				process("http://competitive.na.leagueoflegends.com/ladders/"+country+"/current/ranked_team_3x3");
			}
			
		});
		b = (Button)this.findViewById(R.id.btn_team5x5);
		b.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				state = 1;
				page = 0;
				max_page = 0;
				name_search = false;
				search_name = "";
				game_type = "ranked_team_5x5";
				v.setBackgroundResource(R.drawable.rank_tab_ov);
				RankingBoard.this.findViewById(R.id.btn_team3x3).setBackgroundResource(R.drawable.rank_tab);
				RankingBoard.this.findViewById(R.id.btn_solo5x5).setBackgroundResource(R.drawable.rank_tab);
				((TextView)RankingBoard.this.findViewById(R.id.tv_ladder_name)).setText("Team Name");
				((TextView)RankingBoard.this.findViewById(R.id.tv_search)).setText("Team Name:");
				et_search.setText("");
				process("http://competitive.na.leagueoflegends.com/ladders/"+country+"/current/ranked_team_5x5");
			}
			
		});
		b = (Button)this.findViewById(R.id.btn_solo5x5);
		b.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				state = 2;
				page = 0;
				max_page = 0;
				name_search = false;
				search_name = "";
				game_type = "rankedsolo5x5";
				v.setBackgroundResource(R.drawable.rank_tab_ov);
				RankingBoard.this.findViewById(R.id.btn_team3x3).setBackgroundResource(R.drawable.rank_tab);
				RankingBoard.this.findViewById(R.id.btn_team5x5).setBackgroundResource(R.drawable.rank_tab);
				((TextView)RankingBoard.this.findViewById(R.id.tv_ladder_name)).setText("Player Name");
				((TextView)RankingBoard.this.findViewById(R.id.tv_search)).setText("Summoner Name:");
				et_search.setText("");
				process("http://competitive.na.leagueoflegends.com/ladders/"+country+"/current/rankedsolo5x5");
			}
			
		});
		
		b = (Button)this.findViewById(R.id.rank_name_search);
		b.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				if(et_search.getText().toString().equals("")){
					if(state == 0){
						Utils.showDialog(RankingBoard.this, "LOLDictionary", "Please enter your Team name.");
					}else if(state == 1){
						Utils.showDialog(RankingBoard.this, "LOLDictionary", "Please enter your Team name.");
					}else if(state == 2){
						Utils.showDialog(RankingBoard.this, "LOLDictionary", "Please enter your Summoner name.");	
					}
					return;
				}
				page = 0;
				max_page = 0;
				name_search = true;
				process("http://competitive.na.leagueoflegends.com/ladders/"+country
						+"/current/"+game_type+"?page="+page+"&summoner_name="+et_search.getText().toString());
			}
			
		});
		
		
		
		b = (Button)this.findViewById(R.id.btn_p_first);
		b.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				if(page != 0){
					page = 0;
					max_page = 0;
					String name = "";
					if(!search_name.equals("") && name_search){
						name = "&summoner_name="+search_name;
					}
					process("http://competitive.na.leagueoflegends.com/ladders/"+country
							+"/current/"+game_type+"?page="+page+name);
				}
			}
			
		});
		b = (Button)this.findViewById(R.id.btn_p_prev);
		b.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				if(0 < page){
					page--;
					String name = "";
					if(!search_name.equals("") && name_search){
						name = "&summoner_name="+search_name;
					}
					process("http://competitive.na.leagueoflegends.com/ladders/"+country
							+"/current/"+game_type+"?page="+page+name);
				}
			}
			
		});
		b = (Button)this.findViewById(R.id.rank_page_search);
		b.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				et = new EditText(RankingBoard.this);
				et.setInputType(InputType.TYPE_CLASS_NUMBER);
				new AlertDialog.Builder(RankingBoard.this)
				.setIcon(R.drawable.icon)
				.setTitle("LOLDictionary")
				.setMessage("Enter the search page.("+1+"/"+(max_page+1)+")")
				.setView(et)
				.setPositiveButton("Search", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						if(!et.getText().toString().equals("")){
							int input = 1;
							try{
								input = Integer.parseInt(et.getText().toString());
							}catch(Exception e){
								return;
							}
							if(input >= 1 && input <= max_page){
								page = input-1;
								String name = "";
								if(!search_name.equals("") && name_search){
									name = "&summoner_name="+search_name;
								}
								process("http://competitive.na.leagueoflegends.com/ladders/"+country
										+"/current/"+game_type+"?page="+page+name);
							}
						}
					}
				})
				.setNegativeButton("Close", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
					}
				})
				.create().show();
			}
			
		});
		b = (Button)this.findViewById(R.id.btn_p_next);
		b.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				if(page < max_page){
					page++;
					String name = "";
					if(!search_name.equals("") && name_search){
						name = "&summoner_name="+search_name;
					}
					process("http://competitive.na.leagueoflegends.com/ladders/"+country
							+"/current/"+game_type+"?page="+page+name);
				}
			}
			
		});
		b = (Button)this.findViewById(R.id.btn_p_last);
		b.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				if(page < max_page){
					page = max_page;
					String name = "";
					if(!search_name.equals("") && name_search){
						name = "&summoner_name="+search_name;
					}
					process("http://competitive.na.leagueoflegends.com/ladders/"+country
							+"/current/"+game_type+"?page="+page+name);
				}
			}
			
		});
	}
	
	@Override
    public void onListItemClick(ListView parent, View v, int position, long id) {
		if(state != 2){
			Utils.showDialog(RankingBoard.this, rankArray.get(position).name+" Team Member", 
					rankArray.get(position).teamVal.replaceAll(",", "\r\n"));
		}
	}
	
	final Runnable mSaleUpdate = new Runnable() {
		public void run() {
			if(Utils.isNetwork(RankingBoard.this)){	
				process2();
			}
            new Thread(new Runnable() {
                @Override
                public void run() {    
                    runOnUiThread(new Runnable(){
                        @Override
                         public void run() {
                        	if(rankArray.size() > 0 && name_search && !et_search.getText().toString().equals("")){
                        		search_name = et_search.getText().toString();
                        	}else if(name_search){
                        		et_search.setText(search_name);
                        	}
                     //   	saveRankId();
                        	adapter.notifyDataSetChanged();
                			if (pd != null) {
                				pd.dismiss();
                				pd = null;
                			}
                		//	setAdapter();
                			((Button)RankingBoard.this.findViewById(R.id.rank_page_search)).setText("Page Search\r\n("+(page+1)+"/"+(max_page+1)+")");
                         }
                    });
                }
            }).start(); 
		}

	};
	
	public void process(String url){
		this.url = url;
		if (pd == null) {
			pd = ProgressDialog.show(this, "", "loading Ladder ranking.", true);
			pd.show();
		}
		rankArray.clear();
		Thread t = new Thread(mSaleUpdate);
		t.start();
    }
	
	public void process2(){
		try {
			Source source = new Source(new URL(url));
	    	List<Element> atags = source.getAllElements(HTMLElementName.TR);
	    	RankInfo info = null;
	    	for(int i = 1; i < atags.size(); i++){		
	    		Element e = atags.get(i);
	    		info = new RankInfo();
	    		info.rank = e.getChildElements().get(0).getTextExtractor().toString().trim().replaceAll(",", "");
	    		info.name = e.getChildElements().get(1).getTextExtractor().toString();
	    		if(state != 2){
		    		info.teamVal = " "+e.getChildElements().get(2).getAllElements(HTMLElementName.A).get(0).getAllElements(HTMLElementName.SPAN).get(0).getTextExtractor().toString();	
	    		}
	    		info.win = e.getChildElements().get(3).getTextExtractor().toString().trim().replaceAll(",", "");
	    		info.losses = e.getChildElements().get(4).getTextExtractor().toString().trim().replaceAll(",", "");
	    		info.rating = e.getChildElements().get(5).getTextExtractor().toString().trim().replaceAll(",", "");
	    		rankArray.add(info);
	    	}
	    	atags = source.getAllElements(HTMLElementName.LI);
    		String max_url = "";
	    	for(int i = 0; i < atags.size(); i++){		
	    		Element e = atags.get(i);
	    		if(e.getAttributeValue("class") != null){
	    			if(e.getAttributeValue("class").equals("pager-last last")){
	    				max_url = e.getAllElements(HTMLElementName.A).get(0).getAttributeValue("href");	
	    				break;
	    			}	
	    		}
	    	}
	    	for(int i = max_url.length()-1; i > 0; i--){
	    		if(max_url.substring(i, i+1).equals("=")){
	    			max_page = Integer.parseInt( max_url.substring(i+1, max_url.length()));
	    			break;
	    		}
	    	}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
	
	
	
	class RankInfo{
		String rank;
		String name;
		String win;
		String losses;
		String rating;
		String teamVal;
	}
	
	class ListAdapter extends BaseAdapter{
		
		private Context context;
		private LayoutInflater inflater;
		
		public ListAdapter(Context context) {
			this.context = context;
			inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public int getCount() {
			return rankArray.size();
		}

		@Override
		public Object getItem(int position) {
			return rankArray.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(convertView == null){
				convertView = inflater.inflate(R.layout.ranking_board_row, parent, false);
			}
			RankInfo info = rankArray.get(position);
			if(info != null){
				TextView tv = (TextView)convertView.findViewById(R.id.tv_rank);
				tv.setText(""+info.rank);
				tv = (TextView)convertView.findViewById(R.id.tv_ladder_name);
				tv.setText(""+info.name);
				tv = (TextView)convertView.findViewById(R.id.tv_win);
				tv.setText(""+info.win);
				tv = (TextView)convertView.findViewById(R.id.tv_losses);
				tv.setText(""+info.losses);
				tv = (TextView)convertView.findViewById(R.id.tv_rating);
				tv.setText(""+info.rating);	
			}else{
				TextView tv = (TextView)convertView.findViewById(R.id.tv_rank);
				tv.setText("");
				tv = (TextView)convertView.findViewById(R.id.tv_ladder_name);
				tv.setText("");
				tv = (TextView)convertView.findViewById(R.id.tv_win);
				tv.setText("");
				tv = (TextView)convertView.findViewById(R.id.tv_losses);
				tv.setText("");
				tv = (TextView)convertView.findViewById(R.id.tv_rating);
				tv.setText("");	
			}
			return convertView;
		}
		
	}
	
	public void saveRankId(){
		if(url.equals("http://www.leagueoflegends.co.kr/e-sports/ladder_ranking.php?cate=30") ||
				url.equals("http://www.leagueoflegends.co.kr/e-sports/ladder_ranking.php?cate=31") ||
				url.equals("http://www.leagueoflegends.co.kr/e-sports/ladder_ranking.php?cate=32")){
			return;
		}
		if(rankArray.size() > 0){
			SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
			SharedPreferences.Editor editor = pref.edit();
			for(int i = 0; i < 100; i++){
				String saveName = "";
				if(state == 0){
					saveName = "team_id_"+i;
				}else if(state == 1){
					saveName = "team_id_"+i;
				}else if(state == 2){
					saveName = "rank_id_"+i;
				}
				if(pref.getString(saveName, "").equals("")){
					editor.putString(saveName, et_search.getText().toString());
					break;
				}else if(pref.getString(saveName, "").equals(et_search.getText().toString())){
					break;
				}
			}
			editor.commit();	
		}
	}
	
	public void setAdapter(){
		if(url.equals("http://www.leagueoflegends.co.kr/e-sports/ladder_ranking.php?cate=30") ||
				url.equals("http://www.leagueoflegends.co.kr/e-sports/ladder_ranking.php?cate=31") ||
				url.equals("http://www.leagueoflegends.co.kr/e-sports/ladder_ranking.php?cate=32")){
			return;
		}
		int size = 0;
		String saveName = "";
		if(state == 0){
			saveName = "team_id_";
		}else if(state == 1){
			saveName = "team_id_";
		}else if(state == 2){
			saveName = "rank_id_";
		}
		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		while(!pref.getString(saveName+size, "").equals("")){
			size++;
		}
		String names[] = new String[size];
		for(int i = 0; i < size; i++){
			names[i] = pref.getString(saveName+i, "");
		}
		et_search = (AutoCompleteTextView)findViewById(R.id.et_name);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(
				this, android.R.layout.simple_dropdown_item_1line, names);
		et_search.setAdapter(adapter);
	}
}
